package com.ycl.javacore.exam.limit;

import java.util.concurrent.atomic.AtomicInteger;

public class TPSLimiterTest {
    static AtomicInteger at = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        TPSLimiter limiter = new TPSLimiter(100);

        new Thread(() -> {
            while (true) {
                // 每秒输出一次AtomicInteger的最新值
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(at.get());
            }
        }).start();

        // 启动100个线程对AtomicInteger进行累加，为了方便就没有使用线程池
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                while (true) {
                    // 每次累加操作前先调用await方法，超过设定的ops时会阻塞线程
                    limiter.await();
                    at.incrementAndGet();
                }
            }).start();
        }
    }
}